#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#define PAGELEN 24
#define LINELEN 52

void do_more(FILE *);
int see_more(FILE *);
void set_tty_on();
void set_tty_off();

int main(int ac, char* av[]){
	FILE * fp;
	if (ac == 1){
		do_more(stdin);
	}else{
		while (--ac){
			if ((fp = fopen(* ++av, "r")) != NULL){
				do_more(fp);
				fclose(fp);
			}else{
				exit(1);
			}
		}
	}
	return 0;
}

void do_more(FILE * fp){
	char line[LINELEN];
	int num_of_lines = 0;
	int file_size = 0;
	int cur_size = 0;
	int size = 0;
	fseek(fp, 0L, SEEK_END);
	file_size = ftell(fp);
	fseek(fp, 0L, SEEK_SET);
	int see_more(FILE *), reply;
	FILE *fp_tty;
	fp_tty = fopen("/dev/tty", "r");
	while (fgets(line, LINELEN, fp)){
		if (num_of_lines == PAGELEN){
			printf("								%f%%\n",1.0 * cur_size/file_size*100);
			reply = see_more(fp_tty);
			if (reply == 0){
				break;
			}
			num_of_lines -= reply;
		}
		size = strlen(line);
		cur_size += size;
		if (fputs(line, stdout) == EOF){
			printf("								100%%\n");
			exit(1);
		}
		num_of_lines++;
	}
	printf("								100%%\n");
}

int see_more(FILE * cmd){
   	int c;
	int res;
	printf("\033[7m more \033[m");
	set_tty_off();
	c = getc(cmd);
	set_tty_on();
	if (c == 'q'){
		res = 0;
	}
	if (c == ' '){
		res = PAGELEN;
	}
	if (c == '\n'){
		res = 1;
	}
	return res;
}

void set_tty_off(){
	struct termios new, old;
	int tty = open("/dev/tty",O_RDONLY);
	tcgetattr(tty, &old);
	new = old;
	new.c_lflag &= ~(ICANON | ECHO);
	tcsetattr(tty,TCSANOW,&new);
	close(tty);
}

void set_tty_on(){
	struct termios new, old;
	int tty = open("/dev/tty",O_RDONLY);
	tcgetattr(tty, &old);
	new = old;
	new.c_lflag |= ECHO;
	tcsetattr(tty,TCSANOW,&new);
	close(tty);
}
